package com.books.controller.detail;

import com.books.dao.AnswerDao;
import com.books.dao.NewQuestionDao;
import com.books.dao.QuestionDao;
import com.books.dao.ReplyAnswerDao;
import com.books.mapper.book.BookTypeMapper;
import com.books.model.bo.Result;
import com.books.model.entity.backcontroller.Connection;
import com.books.model.entity.address.Receiving_address;
import com.books.model.entity.book.Books;
import com.books.model.entity.common.People;
import com.books.model.entity.login_regis.UserLogin;
import com.books.model.entity.order.BuyOrder;
import com.books.model.entity.order.OrderList;
import com.books.model.entity.question.Answer;
import com.books.model.entity.question.NewQuestion;
import com.books.model.entity.question.Question;
import com.books.model.entity.question.ReplyAnswer;
import com.books.model.entity.shopping.ShoppingCar;
import com.books.model.tool.*;
import com.books.model.WebSocketProcess;
import com.books.service.address.IAddressService;
import com.books.service.book.IBookService;
import com.books.service.comment.ICommentService;
import com.books.service.connection.IConnectionService;
import com.books.service.order.IBuyOrderServer;
import com.books.service.order.IOrderListServer;
import com.books.service.page.PageService;
import com.books.service.people.IPeopleService;
import com.books.service.shoppingcar.IShoppingCarService;
import net.sf.json.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author 饿熊的咆哮
 * @Date 2021/9/24 19:50
 * @Version 1.0
 */
@Controller
@RequestMapping("/detail")
public class DetailBookController {

    @Autowired
    private IBookService bookService;

    @Autowired
    private BookTypeMapper bookTypeMapper;

    @Autowired
    private ICommentService commentService;

    @Autowired
    private PageService pageService;

    @Autowired
    private IPeopleService peopleService;

    @Autowired
    private IConnectionService connectionService;

    @Autowired
    private IAddressService addressService;

    @Autowired
    private IShoppingCarService shoppingCarService;

    @Autowired
    private QuestionDao questionDao;

    @Autowired
    private AnswerDao answerDao;

    @Autowired
    private ReplyAnswerDao replyAnswerDao;

    @Autowired
    private NewQuestionDao newQuestionDao;

    @Autowired
    private IBuyOrderServer buyOrderServer;

    @Autowired
    private IOrderListServer orderListServer;

    @Autowired
    private WebSocketProcess webSocketProcess;

    @GetMapping("/book")
    public String shopBook(HttpServletRequest request1,Model model, WebRequest request){
        //获取url中的bookId的值
        String bookid = request.getParameter("bookId").trim();
        int bookId = Integer.valueOf(bookid);
        List<Question> questions = questionDao.findTestByName(bookId,1);
        Collections.reverse(questions);
        List<QuestionTool> questionTools = new ArrayList<>();
        for (Question question : questions) {
            People people = peopleService.selectPerson(question.getPId());
            List<Answer> answers = answerDao.findAnswerByQuestionId(question.get_id());
            List<AnswerTool> answerTools = new ArrayList<>();
            for (Answer answer : answers) {
                People people1 = peopleService.selectPerson(answer.getPId());
                List<ReplyAnswer> replyAnswers = replyAnswerDao.findReplyAnswerByAnswerId(answer.get_id());
                List<ReplyAnswerTool> replyAnswerTools = new ArrayList<>();
                for (ReplyAnswer replyAnswer : replyAnswers) {
                    People people2 = peopleService.selectPerson(replyAnswer.getPId());
                    if (replyAnswer.getReplyThisId()==null){
                        ReplyAnswerTool replyAnswerTool = new ReplyAnswerTool(replyAnswer.get_id(),replyAnswer.getAnswerId(),replyAnswer.getReplyThisId(),replyAnswer.getPId(),replyAnswer.getTime(),replyAnswer.getText(),people2.getHeadUrl(),people2.getName(),"该回答");
                        replyAnswerTools.add(replyAnswerTool);
                    }else {
                        ReplyAnswer replyThis = replyAnswerDao.findReplyAnswerById(replyAnswer.getReplyThisId());
                        People replyThisPeople = peopleService.selectPerson(replyThis.getPId());
                        ReplyAnswerTool replyAnswerTool = new ReplyAnswerTool(replyAnswer.get_id(),replyAnswer.getAnswerId(),replyAnswer.getReplyThisId(),replyAnswer.getPId(),replyAnswer.getTime(),replyAnswer.getText(),people2.getHeadUrl(),people2.getName(),"@"+replyThisPeople.getName());
                        replyAnswerTools.add(replyAnswerTool);
                    }
                }
                AnswerTool answerTool = new AnswerTool(answer.get_id(),answer.getQuestionId(),answer.getPId(),answer.getTime(),answer.getText(),people1.getHeadUrl(),people1.getName(),replyAnswerTools);
                answerTools.add(answerTool);
            }
            Collections.reverse(answerTools);
            QuestionTool questionTool = new QuestionTool(question.get_id(),question.getBookId(),question.getBookTypeId(),question.getPId(),question.getTime(),question.getText(),people.getHeadUrl(),people.getName(),answerTools);
            questionTools.add(questionTool);
        }
        JSONArray jsonArrayQuestion = JSONArray.fromObject(questionTools);
        List<CommentTool> commentTools = commentService.findCommentByBookId(bookId,1);
        Boolean just = true;
        HttpSession session = request1.getSession();
        UserLogin user = (UserLogin) session.getAttribute("user");
        Boolean ifCollect = false;
        Boolean ifIn = false;
        if (user != null) {
            Integer peopleId = peopleService.findPeopleId(user.getAccount());
            ifCollect = connectionService.ifCollect(peopleId,bookId,1);
            ifIn = true;
        }
        if (commentTools!=null&&commentTools.size()>0){
            List<CommentTool> pageComment = pageService.findList(commentTools,5,1);
            JSONArray jsonArray = JSONArray.fromObject(pageComment);
            int allPage = pageService.findAllPage(commentTools,5);
            int allComment = commentTools.size();
            model.addAttribute("jsonArray",jsonArray);
            model.addAttribute("allPage",allPage);
            model.addAttribute("allComment",allComment);
        }else {
            model.addAttribute("jsonArray",111111);
            model.addAttribute("allPage",0);
            model.addAttribute("allComment",0);
            just = false;
        }

        if (user!=null){
            Integer peopleId1 = peopleService.findPeopleId(user.getAccount());
            List<NewQuestion> newQuestions = newQuestionDao.findNewQuestionByPeopleId(peopleId1);
            JSONArray newQuestionJson = JSONArray.fromObject(newQuestions);
            model.addAttribute("newQuestions",newQuestionJson);
        }
        Books book = bookService.getById(bookId);
        model.addAttribute("book",book);
        model.addAttribute("just",just);
        model.addAttribute("ifCollect",ifCollect);
        model.addAttribute("ifIn",ifIn);
        model.addAttribute("question",jsonArrayQuestion);
        return "detail/book";
    }

    @GetMapping("/addQuestion")
    @ResponseBody
    public Result addQuestion(Integer bookId,Integer peopleId,String questionText){
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateNowStr = sdf.format(d);
        Question question = new Question();
        // question.set_id(dateNowStr+peopleId);
        question.setBookId(bookId);
        question.setBookTypeId(1);
        question.setPId(peopleId);
        question.setTime(dateNowStr);
        question.setText(questionText);
        questionDao.saveTest(question);
        List<OrderList> orderLists = orderListServer.findByProductId(bookId);
        Map<Integer,People> map = new HashMap<>();
        for (OrderList orderList : orderLists) {
            String buyId = orderList.getBuyId();
            BuyOrder buyOrder = buyOrderServer.findOneOrder(buyId);
            People people = peopleService.selectPerson(buyOrder.getUserId());
            map.put(people.getPeopleId(),people);
        }
        Set<Integer> set = map.keySet();
        Iterator<Integer> iter = set.iterator();
        while (iter.hasNext()){
            Integer key = iter.next();
            try {
                System.out.println(key+"...........................");
                webSocketProcess.sendMessage(key,question);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return new Result("200","提出问题成功");
    }

    @GetMapping("/delNewQuestion")
    @ResponseBody
    public Result delNewQuestion(String newQuestionId){
        newQuestionDao.delById(newQuestionId);
        return new Result("200","删除成功");
    }

    @GetMapping("/answerIt")
    @ResponseBody
    public Result answerIt(Integer bookId,Integer peopleId){
        List<BuyOrder> buyOrders = buyOrderServer.findAllOrder(peopleId);
        for (BuyOrder buyOrder : buyOrders) {
            List<OrderList> orderLists = orderListServer.findAllList(buyOrder.getBuyId());
            for (OrderList orderList : orderLists) {
                if (orderList.getProductId().equals(bookId) && orderList.getBuyType()==1){
                    return new Result("200","请评价");
                }
            }
        }
        return new Result("404","抱歉!您没有购买过此书!!无法回答!!!");
    }

    @GetMapping("/answerTheQuestion")
    @ResponseBody
    public Result answerTheQuestion(String questionId,Integer peopleId,String text){
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateNowStr = sdf.format(d);
        Answer answer = new Answer();
        answer.setQuestionId(questionId);
        answer.setPId(peopleId);
        answer.setTime(dateNowStr);
        answer.setText(text);
        answerDao.addAnswer(answer);
        return new Result("200","回答成功");
    }

    @GetMapping("/repayTheAnswer")
    @ResponseBody
    public Result repayTheAnswer(Integer peopleId,String text,String answerId){
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateNowStr = sdf.format(d);
        ReplyAnswer replyAnswer = new ReplyAnswer();
        replyAnswer.setAnswerId(answerId);
        replyAnswer.setPId(peopleId);
        replyAnswer.setTime(dateNowStr);
        replyAnswer.setText(text);
        replyAnswerDao.addReplyAnswer(replyAnswer);
        return new Result("200","回复成功");
    }

    @GetMapping("/repayTheReply")
    @ResponseBody
    public Result repayTheReply(Integer peopleId,String text,String answerId,String replyId){
        Date d = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String dateNowStr = sdf.format(d);
        ReplyAnswer replyAnswer = new ReplyAnswer();
        replyAnswer.setAnswerId(answerId);
        replyAnswer.setReplyThisId(replyId);
        replyAnswer.setPId(peopleId);
        replyAnswer.setTime(dateNowStr);
        replyAnswer.setText(text);
        replyAnswerDao.addReplyAnswer(replyAnswer);
        return new Result("200","回复成功");
    }

    @GetMapping("/getNowComment")
    @ResponseBody
    public JSONArray getNowComment(Integer nowPage,Integer bookId){
        List<CommentTool> commentTools = commentService.findCommentByBookId(bookId,1);
        List<CommentTool> pageComment = pageService.findList(commentTools,5,nowPage);
        JSONArray jsonArray = JSONArray.fromObject(pageComment);
        return jsonArray;
    }

    @GetMapping("/getBookType")
    @ResponseBody
    public String getBookType(Integer typeId){
        String bookType = bookTypeMapper.findById(typeId).getCategoryName();
        return bookType;
    }

    @GetMapping("/collect")
    @ResponseBody
    public Result collect(HttpServletRequest request, String bookId){
        HttpSession session = request.getSession();
        UserLogin user = (UserLogin) session.getAttribute("user");
        if (user == null) {
            return new Result("500", "请先登陆！");
        } else {
            Integer peopleId = peopleService.findPeopleId(user.getAccount());
            connectionService.addConnection(new Connection(null,peopleId,Integer.valueOf(bookId),1));
            return new Result("200","收藏成功");
        }
    }

    @GetMapping("/delCollect")
    @ResponseBody
    public Result delCollect(HttpServletRequest request, String bookId){
        HttpSession session = request.getSession();
        UserLogin user = (UserLogin) session.getAttribute("user");
        if (user == null) {
            return new Result("500", "请先登陆！");
        } else {
            Integer peopleId = peopleService.findPeopleId(user.getAccount());
            connectionService.delByAll(peopleId,Integer.valueOf(bookId),1);
            return new Result("200","取消收藏成功");
        }
    }

    @GetMapping("/buyMore")
    @ResponseBody
    public Result buyMore(HttpServletRequest request){
        HttpSession session = request.getSession();
        UserLogin user = (UserLogin) session.getAttribute("user");
        if (user == null) {
            return new Result("500", "请先登陆！");
        } else {
            return new Result("200","登陆中");
        }
    }

    @GetMapping("/bookAndAddress")
    @ResponseBody
    public Result bookAndAddress(HttpServletRequest request,Integer peopleId,Integer bookId,Integer buyNum){
        HttpSession session=request.getSession();
        List<Receiving_address> addressList=addressService.findAllByPid(peopleId);
        session.setAttribute("addresslist",addressList);
        List<ShoppingCar> car=new ArrayList<>();
        int shopCarId = Integer.valueOf(peopleId+""+bookId+"1");
        Books books = bookService.getById(bookId);
        Double total = books.getPrice()*buyNum;
        ShoppingCar shoppingCar = new ShoppingCar(shopCarId,bookId,books.getTitle(),books.getPictureUrl(),books.getPrice(),buyNum,"1",total,peopleId,1);
        // System.out.println(shoppingCar);
        car.add(shoppingCar);
        session.setAttribute("carlist",car);
        return new Result("200","已选择商品");
    }
}
